 // Engine Time Control
////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Engine.h"

// the number of miliseconds we should report the progress
#define PROGRESS_TIME_STEP   500


// initializes the time control
void InitTimeControl(SEngineData* ed, DWORD dwMaxTime)
{
	// get the current time
	ed->dwStartTime = ::GetTickCount();
	ed->dwTerminateTime = ed->dwStartTime + dwMaxTime;
	ed->dwMaxTime = dwMaxTime;
	ed->dwProgressTimeStep = PROGRESS_TIME_STEP;
	ed->dwLastProgressTime = ed->dwStartTime;
}

// checks whether we have run out of time
bool CheckTime(SEngineData* ed)
{
	// check the number of nodes - GetTickCount is too slow to check every node
	if( (ed->iNumberOfNodes & 0x3FF) == 0  && ed->dwMaxTime)
	{
		DWORD dwCurrentTime = GetTickCount();

		// check progress
		if(ed->bEngineReportProgress)
		{
			if(dwCurrentTime - ed->dwLastProgressTime > ed->dwProgressTimeStep)
			{
				DWORD percent = (dwCurrentTime - ed->dwStartTime) / (ed->dwMaxTime / 100);
				ed->dwLastProgressTime = dwCurrentTime;
				if(ed->EnginePercentProgress != NULL)
					ed->EnginePercentProgress(percent, ed->pReportFuncData);
			}
		}

		// check end of computing
		if(dwCurrentTime >= ed->dwTerminateTime)
		{
			return true;
		}
	}

	return false;
}

